﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Security.Permissions;
using System.Security;

namespace ThiTracNghiem
{
    public partial class FormBackup : Form
    {
        public FormBackup()
        {
            InitializeComponent();
            cbType.SelectedIndex = 0;
        }

        private void FormBackup_Load(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection(Program.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM sys.backup_devices", con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        cbDevice.Items.Add(reader[0].ToString());
                    }
                }
            }

            txtFileLocation.Text = Application.StartupPath + @"\TracNghiemBackupDb.bak";
        }

        private void cbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbType.SelectedIndex == 0)
            {
                txtTen.Text = "TRAC_NGHIEM-Full Database Backup";
            }
            else if (cbType.SelectedIndex == 1)
            {
                txtTen.Text = "TRAC_NGHIEM-Differential Database Backup";
            }
            else
            {
                txtTen.Text = "TRAC_NGHIEM-Transaction Log  Backup";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void rbDevice_CheckedChanged(object sender, EventArgs e)
        {
            if (rbDevice.Checked)
            {
                cbDevice.Enabled = true;
                btnRefresh.Enabled = true;
                btnBrowse.Enabled = false;
            }
            else
            {
                cbDevice.Enabled = false;
                btnRefresh.Enabled = false;
                btnBrowse.Enabled = true;
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            cbDevice.Items.Clear();
            using (SqlConnection con = new SqlConnection(Program.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM sys.backup_devices", con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        cbDevice.Items.Add(reader[0].ToString());
                    }
                }
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (cbType.SelectedIndex < 0)
            {
                return;
            }

            if (rbDevice.Checked && cbDevice.SelectedIndex < 0)
            {
                MessageBox.Show("Để thực hiện backup bạn phải chọn file hoặc 1 device để backup đến.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //PermissionSet ps = new PermissionSet(PermissionState.None);
            //ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, txtFileLocation.Text.Trim()));

            int type = 0;
            String dest = "";

            if (rbFile.Checked)
            {
                // FILE
                dest = txtFileLocation.Text.Trim();
                type = cbType.SelectedIndex;
            }
            else
            {
                dest = cbDevice.SelectedItem.ToString().Trim();
                type = cbType.SelectedIndex + 3;
            }

            using (SqlConnection con = new SqlConnection(Program.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SP_BACKUP_DB", con))
                {
                    try
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@FILEORDEVICE", SqlDbType.Int).Value = type;
                        cmd.Parameters.Add("@NAME", SqlDbType.NVarChar).Value = txtTen.Text.Trim();
                        cmd.Parameters.Add("@DESCRIPTION", SqlDbType.NVarChar).Value = txtMoTa.Text.Trim();
                        cmd.Parameters.Add("@DEST", SqlDbType.NVarChar).Value = dest;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        for (int i = progress.Minimum; i < progress.Maximum; i++ )
                        {
                            progress.Value++;
                        }

                        MessageBox.Show("Thực hiện backup database thành công!", "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Dispose();

                    }
                    catch (SqlException ex)
                    {
                        if (ex.Number == 3201)
                        {
                            MessageBox.Show("Permission error. Bạn không có quyền truy xuất đến file backup này.\nVui lòng chọn file backup khác.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            MessageBox.Show("Có lỗi đã xảy ra.\nChi tiết: " + ex.Number, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Có lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            saveBakFileDialog.Filter = "Backup File(*.bak)|*.bak";
            saveBakFileDialog.InitialDirectory = Path.GetDirectoryName(txtFileLocation.Text.Trim());
            saveBakFileDialog.FileName = Path.GetFileName(txtFileLocation.Text.Trim());

            if (saveBakFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFileLocation.Text = saveBakFileDialog.FileName;
            }
        }

        private void btnDeviceManager_Click(object sender, EventArgs e)
        {
            FormDeviceMgr frmDeviceMgr = new FormDeviceMgr();
            frmDeviceMgr.Owner = this.Owner;
            frmDeviceMgr.Show();
        }
    }
}
